﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using FluentValidation;

using ERPStore.Extensions;

using CloudSoft.Extensions;

namespace ERPStore.Coupons.ModelValidators
{
	public class CouponValidator : AbstractValidator<Models.Coupon>
	{
		public CouponValidator(Services.AdminIncentiveService incentiveService)
		{
			RuleFor(p => p.Code).NotEmpty().WithMessage("Le code du coupon doit etre indiqué");
			Custom(p =>
				{
					if (p.Code.IsNullOrEmpty()
						&& p.Code.Length > 50)
					{
						return new FluentValidation.Results.ValidationFailure("Code", "Le code ne doit pas exceder 50 caractères");
					}
					return null;
				});
			RuleFor(p => p.ProviderName).NotEmpty().WithMessage("providername is required");
			RuleFor(p => p.Description).NotEmpty().WithMessage("Une description doit etre indiquée");
			Custom(settings =>
				{
					if (settings.MaximumUseCount.HasValue)
					{
						if (settings.MaximumUseCount.Value < 0)
						{
							return new FluentValidation.Results.ValidationFailure("MaximumUseCount", "Le nombre maxi d'utilisation doit etre supérieur à zero");
						}
					}
					return null;
				});
			Custom(settings =>
				{
					var list = incentiveService.GetCouponProviderList();
					if (!list.Any(p => p.Name.Equals(settings.ProviderName, StringComparison.InvariantCultureIgnoreCase)))
					{
						return new FluentValidation.Results.ValidationFailure("providername", "Ce fournisseur de coupon n'existe pas");
					}
					return null;
				});
			Custom(settings =>
				{
					if (settings.ProviderName == "creditdiscount")
					{
						if (!settings.CreditAmount.HasValue)
						{
							return new FluentValidation.Results.ValidationFailure("CreditAmount", "Un montant de remise doit etre indiqué");
						}
						else if (settings.CreditAmount.Value <= 0)
						{
							return new FluentValidation.Results.ValidationFailure("CreditAmount", "Le montant de la remise doit etre supérieur à zero");
						}
					}
					return null;
				});
		}
	}
}
